// 门票管理页面
const app = getApp();
const request = require('../../../../utils/request.js').request;

Page({
  data: {
    scenicAreaId: null,
    scenicAreaName: '',
    loading: true,
    tickets: [],
    showAddForm: false,
    showEditForm: false,
    currentTicket: null,
    formData: {
      id: '',
      scenicAreaId: '',
      name: '',
      price: '',
      validDays: 1,
      description: '',
      totalQuantity: 0,
      availableQuantity: 0
    }
  },

  onLoad: function (options) {
    // 获取URL参数
    const { scenicAreaId, scenicAreaName } = options;
    
    this.setData({
      scenicAreaId,
      scenicAreaName
    });
    
    // 加载门票列表
    this.loadTickets();
  },

  onPullDownRefresh: function () {
    this.loadTickets();
  },

  // 加载门票列表
  loadTickets: function () {
    this.setData({ loading: true });
    
    request({
      url: `/api/ticket/scenic/${this.data.scenicAreaId}`,
      method: 'GET',
      success: (res) => {
        if (res.code === 0) {
          this.setData({
            tickets: res.data,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.msg || '获取门票列表失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      },
      complete: () => {
        wx.stopPullDownRefresh();
      }
    });
  },

  // 显示添加表单
  showAddForm: function () {
    this.setData({
      showAddForm: true,
      formData: {
        id: '',
        scenicAreaId: this.data.scenicAreaId,
        name: '',
        price: '',
        validDays: 1,
        description: '',
        totalQuantity: 0,
        availableQuantity: 0
      }
    });
  },

  // 显示编辑表单
  showEditForm: function (e) {
    const index = e.currentTarget.dataset.index;
    const ticket = this.data.tickets[index];
    
    this.setData({
      showEditForm: true,
      currentTicket: ticket,
      formData: {
        id: ticket.id,
        scenicAreaId: this.data.scenicAreaId,
        name: ticket.name,
        price: ticket.price,
        validDays: ticket.validDays,
        description: ticket.description || '',
        totalQuantity: ticket.totalQuantity || 0,
        availableQuantity: ticket.availableQuantity || 0
      }
    });
  },

  // 关闭表单
  closeForm: function () {
    this.setData({
      showAddForm: false,
      showEditForm: false
    });
  },

  // 输入表单数据
  inputChange: function (e) {
    const { field } = e.currentTarget.dataset;
    let { formData } = this.data;
    formData[field] = e.detail.value;
    this.setData({ formData });
  },

  // 提交添加表单
  submitAddForm: function () {
    const { formData } = this.data;
    
    if (!formData.name || !formData.price) {
      wx.showToast({
        title: '门票名称和价格不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 验证数量是否合法
    if (parseInt(formData.totalQuantity) < parseInt(formData.availableQuantity)) {
      wx.showToast({
        title: '可用数量不能大于总数量',
        icon: 'none'
      });
      return;
    }
    
    // 构建正确的请求数据结构，确保与后端接口匹配
    const requestData = {
      name: formData.name,
      price: parseFloat(formData.price),
      validDays: parseInt(formData.validDays),
      description: formData.description,
      totalQuantity: parseInt(formData.totalQuantity),
      availableQuantity: parseInt(formData.availableQuantity),
      scenicArea: {
        id: parseInt(formData.scenicAreaId)
      }
    };
    
    request({
      url: '/api/ticket/add',
      method: 'POST',
      data: requestData,
      success: (res) => {
        if (res.code === 0) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
          this.setData({ showAddForm: false });
          this.loadTickets();
        } else {
          wx.showToast({
            title: res.msg || '添加失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 提交编辑表单
  submitEditForm: function () {
    const { formData } = this.data;
    
    if (!formData.name || !formData.price) {
      wx.showToast({
        title: '门票名称和价格不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 验证数量是否合法
    if (parseInt(formData.totalQuantity) < parseInt(formData.availableQuantity)) {
      wx.showToast({
        title: '可用数量不能大于总数量',
        icon: 'none'
      });
      return;
    }
    
    // 构建正确的请求数据结构，确保与后端接口匹配
    const requestData = {
      name: formData.name,
      price: parseFloat(formData.price),
      validDays: parseInt(formData.validDays),
      description: formData.description,
      totalQuantity: parseInt(formData.totalQuantity),
      availableQuantity: parseInt(formData.availableQuantity),
      scenicArea: {
        id: parseInt(formData.scenicAreaId)
      }
    };
    
    request({
      url: `/api/ticket/${formData.id}`,
      method: 'PUT',
      data: requestData,
      success: (res) => {
        if (res.code === 0) {
          wx.showToast({
            title: '更新成功',
            icon: 'success'
          });
          this.setData({ showEditForm: false });
          this.loadTickets();
        } else {
          wx.showToast({
            title: res.msg || '更新失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 删除门票
  deleteTicket: function (e) {
    const index = e.currentTarget.dataset.index;
    const ticket = this.data.tickets[index];
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除门票"${ticket.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          request({
            url: `/api/ticket/${ticket.id}`,
            method: 'DELETE',
            success: (res) => {
              if (res.code === 0) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                this.loadTickets();
              } else {
                wx.showToast({
                  title: res.msg || '删除失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 更新门票数量
  updateTicketQuantity: function(e) {
    const index = e.currentTarget.dataset.index;
    const ticket = this.data.tickets[index];
    
    // 创建临时数据对象
    const tempData = {
      id: ticket.id,
      totalQuantity: ticket.totalQuantity || 0,
      availableQuantity: ticket.availableQuantity || 0
    };
    
    // 直接弹出总数量输入框
    wx.showModal({
      title: '总数量',
      content: '请输入门票总数量',
      editable: true,
      placeholderText: String(tempData.totalQuantity),
      success: (res) => {
        if (res.confirm && res.content) {
          tempData.totalQuantity = parseInt(res.content);
          
          // 然后弹出可用数量输入框
          wx.showModal({
            title: '可用数量',
            content: '请输入可用数量（不能超过总数量）',
            editable: true,
            placeholderText: String(Math.min(tempData.availableQuantity, tempData.totalQuantity)),
            success: (res2) => {
              if (res2.confirm && res2.content) {
                tempData.availableQuantity = parseInt(res2.content);
                
                // 校验数据
                if (tempData.availableQuantity > tempData.totalQuantity) {
                  wx.showToast({
                    title: '可用数量不能超过总数量',
                    icon: 'none'
                  });
                  return;
                }
                
                // 提交更新
                this.submitUpdateQuantity(tempData);
              }
            }
          });
        }
      }
    });
  },
  
  // 提交数量更新
  submitUpdateQuantity: function(data) {
    wx.showLoading({
      title: '更新中...',
    });
    
    // 准备请求数据
    const requestData = {
      totalQuantity: data.totalQuantity,
      availableQuantity: data.availableQuantity
    };
    
    request({
      url: `/api/ticket/quantity/${data.id}`,
      method: 'PUT',
      data: requestData,
      success: (res) => {
        if (res.code === 0) {
          wx.showToast({
            title: '数量更新成功',
            icon: 'success'
          });
          // 刷新数据
          this.loadTickets();
        } else {
          wx.showToast({
            title: res.msg || '更新失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
}) 